﻿from pycad.system import *
from pycad.runtime import *

from NFox.Expression.DataSystem import *
from NFox.Expression.Runtime import *
from NFox.Expression.SymbolValues import *

#加载局部cui
pye.loadcuix('parts', 'parts.cuix')

#初始化数据
Application.WorkingDatabase = Database(pye.findfile(__name__, 'parts.odx'))

def partdefining(sender, e):
    from ctypes import windll
    windll.user32.SetActiveWindow(acap.Application.MainWindow.Handle)
    respt = ed.GetPoint('\n指定插入基点')
    if respt.Status == aced.PromptStatus.OK:
        pt = respt.Value
        opts = aced.PromptSelectionOptions()
        opts.MessageForAdding = '\n请选择曲线或文字:'
        resss = ed.GetSelection(opts, conv.ToFilter([[0, 'line,circle,ellipse,arc,lwpolyline,spline,*text']]))
        if resss.Status == PromptStatus.OK:
            from System.Collections.Generic import List
            ents = List[acdb.Entity]()
            with dbtrans() as tr:
                mat = acge.Matrix3d.Displacement(acge.Point3d.Origin - pt)
                for i in resss.Value.GetObjectIds():
                    copy = tr.getobject(i).Clone()
                    copy.TransformBy(mat)
                    ents.Add(copy)
            e.Part = ImagePart()
            e.Part.Image = Image2D(ents)

def dragstart(sender, e):
    if e.Part:
        part = e.Part
        import clr
        clr.AddReference('System.Windows.Forms')
        from System.Windows.Forms import DataObject, DragDropEffects
        data = DataObject()
        data.SetData(SymbolIndex, part.Index)
        acap.Application.DoDragDrop(sender, data, DragDropEffects.Move, PartDropTarget())


class PartDropTarget(acws.DropTarget):
    def OnDrop(self, e):
        from ctypes import windll
        windll.user32.SetActiveWindow(acap.Application.MainWindow.Handle)
        index = e.Data.GetData(SymbolIndex)
        ed()
        ed.Document.SendStringToExecute('Tls:InsertPart\n%s\n%s\n' % (index.DictionaryName, index.Key), False, False, False)


_plv = PartListView()
_plv.Root = Application.WorkingDatabase.Root
_plv.DragStart += Part.EventHandler(dragstart)
_plv.PartDefining += partdefining
_lastIndex = None

@panel('600420e2-5a0c-4935-8f3a-d5714531cd11', 'Tls:ShowPartListView')
class ShowPartListView(object):
    text = '预览零件库'
    dockside = acws.DockSides.Right
    def __init__(self, ps):
        import clr
        clr.AddReference('System.Drawing')
        from System.Drawing import Size
        ps.Style = \
            acws.PaletteSetStyles.NameEditable | \
            acws.PaletteSetStyles.ShowCloseButton | \
            acws.PaletteSetStyles.Notify
        ps.DockEnabled = acws.DockSides.Right
        ps.MinimumSize = Size(320, 320)
        global _plv
        ps.Add("P1", _plv)

    def __docking__(self, ps):
        from System.Drawing import Size
        ps.Size = Size(320, 640)